﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using CloudTaobao.Util;
using System.Text;

namespace CloudTaobao
{
    public class Find
    {
        private const string strSession = "session";
        private const string strFields = "fields";

        public int currentItemPage = 1;
        public int totalItems = 0;
        public int currentShopPage = 1;
        public int totalShops = 0;
        public int currentTradePage = 1;
        public int totalTrades = 0;
        public int currentTradeRatePage = 1;
        public int totalTradeRate = 0;
        public int showMessagePage = 1;

        public filterParams filter;
        private AutoLogin autoLogin;

        public event GetItemBriefFinishedEventHandler getItemBriefFinishedEvent;
        public event GetItemDetialFinishedEventHandler getItemDetialFinishedEvent;
        public event StartLoadingEventHandler startLoadingEvent;
        public event EndLoadingEventHandler endLoadingEvent;
        #region Accessors
        public ObservableCollection<User> userList{get;set;}
        public ObservableCollection<Item> itemList{get;set;}
        public ObservableCollection<TradeRecord> tradeList{get;set;}
        public TransForm transForm{get;set;}
        public ObservableCollection<Item> taokeItemList{get;set;}
        public ObservableCollection<TradeRate> tradeRateList{get;set;}
        public ObservableCollection<Contactor> recentContactorList{get;set;}
        public ObservableCollection<WangMessage> messageList { get; set; }
        #endregion

        public Find()
        {
            filter = new filterParams();
            autoLogin = new AutoLogin();
            userList = new ObservableCollection<User>();
            itemList = new ObservableCollection<Item>();
            tradeList = new ObservableCollection<TradeRecord>();
            taokeItemList = new ObservableCollection<Item>();
            tradeRateList = new ObservableCollection<TradeRate>();
            recentContactorList = new ObservableCollection<Contactor>();
            messageList = new ObservableCollection<WangMessage>();
            transForm = new TransForm();
            autoLogin.autoLoginFinishedEvent += new AutoLoginFinishedEventHandler(autoLogin_autoLoginFinishedEvent);
            autoLogin.startLoadingEvent += new StartLoadingEventHandler(autoLogin_startLoadingEvent);
            autoLogin.endLoadingEvent += new EndLoadingEventHandler(autoLogin_endLoadingEvent);
        }

        void autoLogin_endLoadingEvent()
        {
            endLoadingEvent();
        }

        void autoLogin_startLoadingEvent(object source, StartLoadingEventArgs args)
        {
            startLoadingEvent(this,args);
        }

        void autoLogin_autoLoginFinishedEvent()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show("会话过期--囧rz，已经完成自动重新登录，请重新执行您想做的操作^_^");
            });
        }

        private void handleInValidSessionException()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                endLoadingEvent();

                AppSettings settings = new AppSettings();
                settings.valid = false;
                settings.top_session = "";
                MessageBox.Show("Session可能已过期，请后退到主界面重新登录");
                
                //autoLogin.autoLogin(settings.token);
            });
        }

        private void handleCommonException(Exception e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                endLoadingEvent();
                MessageBox.Show(e.Message);
            });
        }

        public void GetUserInfo(string nickName)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();

            client.addParameter(strFields, "uid,nick,created,buyer_credit,seller_credit,location,promoted_type,avatar,email");
            client.addParameter("method", "taobao.user.get");
            client.addParameter("nick", nickName);
            if (app.sessionInfo.ContainsKey("top_session") && !app.sessionInfo["top_session"].Equals(""))
            {
                client.addParameter(strSession, app.sessionInfo["top_session"]);
            }

            client.sendRequest(new AsyncCallback(HandleBasicInfoResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在载入用户信息"));
        }

        public void GetItemList(string q, int page, int pageSize, bool isShowPic)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();
            string pic;
            if (isShowPic)
                pic = ",pic_url";
            else
                pic = "";
            client.addParameter(strFields, "num_iid,title,nick,volume,promoted_service,is_prepay,price,post_fee,score" + pic);
            client.addParameter("method", "taobao.items.search");
            client.addParameter("q", q);
            client.addParameter("page_no", "" + page);
            client.addParameter("page_size", "" + pageSize);
            client.addParameter("order_by", filter.order_by);
            if (filter.is_cod != "no") 
            {
                client.addParameter("is_cod", filter.is_cod);
            }
            if (filter.is_prepay != "no")
            {
                client.addParameter("is_prepay", filter.is_prepay);
            }
            if (filter.promoted_service != "no")
            {
                client.addParameter("promoted_service", filter.promoted_service);
            }
            if (filter.stuff_status != "no")
            {
                client.addParameter("stuff_status", filter.stuff_status);
            }
            if (filter.start_price != "no")
            {
                client.addParameter("start_price", filter.start_price);
            }
            if (filter.end_price != "no")
            {
                client.addParameter("end_price", filter.end_price);
            }

            client.sendRequest(new AsyncCallback(HandleItemListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取商品列表"));
        }

        public void GetItem(string num_iid, string nick,bool isBreif, bool bIncludePic = true)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();

            if (isBreif)
            {
                string param = "wap_detail_url,type,skus,num,stuff_status,location,express_fee,ems_fee,freight_payer,score";
                if (bIncludePic)
                    param += ",pic_url";
                client.addParameter(strFields, param);
            }
            else 
            {
                client.addParameter(strFields, "wap_desc");
            }
            client.addParameter("method", "taobao.item.get");
            client.addParameter("num_iid", num_iid);
            if (nick != null && nick != "")
            {
                client.addParameter("nick", nick);
            }

            client.sendRequest(new AsyncCallback(HandleGetItemResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取商品信息"));
        }

        public void GetTradeList(int page, int pageSize)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();

            client.addParameter(strFields, "tid,orders.title,seller_nick,status,num_iid");
            client.addParameter("method", "taobao.trades.bought.get");
            client.addParameter("page_no", "" + page);
            client.addParameter("page_size", "" + pageSize);
            if (app.sessionInfo["top_session"] == "")
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Session可能已过期，请后退到主界面重新登录");
                });
                return;
            }
            client.addParameter(strSession, app.sessionInfo["top_session"]);
            client.sendRequest(new AsyncCallback(HandleGetTradeListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取交易列表"));
        }

        public void GetTransFormList(string tid, string seller_nick)
        {
            transForm.out_sid = "";
            transForm.company_name = "";
            transForm.status = "";
            transForm.transitStepInfos.Clear();
            if (tid == "" || seller_nick == "")
            {
                MessageBox.Show("交易或卖家不存在");
                return;
            }
            App app = Application.Current as App;
            TOPClient client = new TOPClient();

            client.addParameter("method", "taobao.logistics.trace.search");
            client.addParameter("tid", "" + tid);
            client.addParameter("seller_nick", "" + seller_nick);
            if (app.sessionInfo["top_session"] != "")
            {
                client.addParameter(strSession, app.sessionInfo["top_session"]);
            }
            client.sendRequest(new AsyncCallback(HandleGetTransFormResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取物流信息"));
        }

        public void GetTaokeItemList(int pageSize)
        {
            App app = Application.Current as App;
            AppSettings settings = new AppSettings();
            TOPClient client = new TOPClient();

            client.addParameter(strFields, "num_iid,pic_url,click_url,price");
            client.addParameter("method", "taobao.taobaoke.items.get");
            client.addParameter("keyword", settings.query);
            client.addParameter("page_no", "1");
            client.addParameter("page_size", "" + pageSize);
            client.addParameter("nick", "bingtangx");
            client.addParameter("sort", "commissionNum_desc");
            client.addParameter("is_mobile", "true");

            client.sendRequest(new AsyncCallback(HandleTaokeItemListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取商品列表"));
        }

        public void GetTradeRateList(string seller_nick, string num_iid, int page, int pageSize)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();

            client.addParameter("method", "taobao.traderates.search");
            client.addParameter("num_iid", num_iid);
            client.addParameter("page_no", "" + page);
            client.addParameter("page_size", "" + pageSize);
            client.addParameter("seller_nick", seller_nick);
            
            client.sendRequest(new AsyncCallback(HandleTradeRateListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取评论列表"));
        }

        public void GetRecentContactor()
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();
            if (app.sessionInfo["top_session"] == "")
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Session可能已过期，请后退到主界面重新登录");
                });
                return;
            }
            client.addParameter(strSession, app.sessionInfo["top_session"]);
            client.addParameter("method", "taobao.wangwang.eservice.chatpeers.get");
            client.addParameter("chat_id", "cntaobao" + app.sessionInfo["nick"]);
            client.addParameter("start_date", DateTime.Now.AddDays(-6).Date.ToString("yyyy-MM-dd"));
            client.addParameter("end_date", DateTime.Now.Date.ToString("yyyy-MM-dd"));
            //client.addParameter("charset", "utf-8");
            
            client.sendRequest(new AsyncCallback(HandleGetRecentContactorListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取联系人列表"));
        }

        public void GetMessageList(string toUser)
        {
            App app = Application.Current as App;
            TOPClient client = new TOPClient();
            if (app.sessionInfo["top_session"] == "")
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Session可能已过期，请后退到主界面重新登录");
                });
                return;
            }
            client.addParameter(strSession, app.sessionInfo["top_session"]);
            client.addParameter("method", "taobao.wangwang.eservice.chatlog.get");
            client.addParameter("from_id", "cntaobao" + app.sessionInfo["nick"]);
            client.addParameter("to_id", toUser);
            client.addParameter("start_date", DateTime.Now.AddDays(-6 * showMessagePage).Date.ToString("yyyy-MM-dd"));
            client.addParameter("end_date", DateTime.Now.Date.ToString("yyyy-MM-dd"));

            client.sendRequest(new AsyncCallback(HandleGetMessageListResponse));
            startLoadingEvent(this, new StartLoadingEventArgs("正在获取消息列表"));
        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleBasicInfoResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }
                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                if (xmlBasic.Element("user") != null)
                {
                    User tmpUser = new User();
                    XElement xmlCurrent = xmlBasic.Descendants("user").First();
                    if (xmlCurrent.Element("nick") != null)
                    {
                        tmpUser.nickName = xmlCurrent.Element("nick").Value;
                    }
                    if (xmlCurrent.Element("created") != null)
                    {
                        tmpUser.Created = xmlCurrent.Element("created").Value;
                    }
                    if (xmlCurrent.Element("avatar") != null)
                    {
                        tmpUser.Avatar = xmlCurrent.Element("avatar").Value;
                    }
                    if (xmlCurrent.Element("email") != null)
                    {
                        tmpUser.Email = xmlCurrent.Element("email").Value;
                    }
                    if (xmlCurrent.Element("uid") != null)
                    {
                        tmpUser.UID = xmlCurrent.Element("uid").Value;
                    }
                    if (xmlCurrent.Element("location") != null)
                    {
                        XElement xmlNext = xmlBasic.Descendants("location").First();
                        if (xmlNext.Element("zip") != null)
                        {
                            tmpUser.Location.zip = xmlNext.Element("zip").Value;
                        }
                        if (xmlNext.Element("state") != null)
                        {
                            tmpUser.Location.state = xmlNext.Element("state").Value;
                        }
                        if (xmlNext.Element("city") != null)
                        {
                            tmpUser.Location.city = xmlNext.Element("city").Value;
                        }
                    }
                    if (xmlCurrent.Element("buyer_credit") != null)
                    {
                        XElement xmlNext = xmlBasic.Descendants("buyer_credit").First();
                        if (xmlNext.Element("good_num") != null)
                        {
                            tmpUser.buyerCredit.good_num = xmlNext.Element("good_num").Value;
                        }
                        if (xmlNext.Element("level") != null)
                        {
                            tmpUser.buyerCredit.level = xmlNext.Element("level").Value;
                        }
                        if (xmlNext.Element("score") != null)
                        {
                            tmpUser.buyerCredit.score = xmlNext.Element("score").Value;
                        }
                        if (xmlNext.Element("total_num") != null)
                        {
                            tmpUser.buyerCredit.total_num = xmlNext.Element("total_num").Value;
                        }
                    }
                    if (xmlCurrent.Element("seller_credit") != null)
                    {
                        XElement xmlNext = xmlBasic.Descendants("seller_credit").First();
                        if (xmlNext.Element("good_num") != null)
                        {
                            tmpUser.sellerCredit.good_num = xmlNext.Element("good_num").Value;
                        }
                        if (xmlNext.Element("level") != null)
                        {
                            tmpUser.sellerCredit.level = xmlNext.Element("level").Value;
                        }
                        if (xmlNext.Element("score") != null)
                        {
                            tmpUser.sellerCredit.score = xmlNext.Element("score").Value;
                        }
                        if (xmlNext.Element("total_num") != null)
                        {
                            tmpUser.sellerCredit.total_num = xmlNext.Element("total_num").Value;
                        }
                    }

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        userList.Clear();
                        // copy the list over
                        userList.Add(tmpUser);
                        endLoadingEvent();

                    });
                }
            }
            catch (InValidSessionException)
            {
                handleInValidSessionException();
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleItemListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                totalItems = 0;
                if (xmlBasic.Element("total_results") != null)
                {
                    totalItems = Convert.ToInt32(xmlBasic.Element("total_results").Value);
                }
                if (totalItems == 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("没有找到符合搜索条件的商品");
                        endLoadingEvent();
                    });
                    return;
                }
                if (xmlBasic.Element("item_search") == null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                    });
                    return;
                }
                xmlBasic = xmlBasic.Element("item_search");
                ObservableCollection<Item> tmpItemList = new ObservableCollection<Item>();

                
                if (xmlBasic.Element("items") != null)
                {
                    

                    XElement xmlCurrent = xmlBasic.Descendants("items").First();
                    IEnumerator<XElement> items = xmlCurrent.Descendants("item").GetEnumerator();
                    while (items.MoveNext())
                    {
                        Item tmpItem = new Item();
                        if (items.Current.Element("num_iid") != null)
                        {
                            tmpItem.num_iid = items.Current.Element("num_iid").Value;
                        }
                        if (items.Current.Element("title") != null)
                        {
                            tmpItem.title = Utils.filterSpanString(items.Current.Element("title").Value);
                        }
                        if (items.Current.Element("nick") != null)
                        {
                            tmpItem.nick = items.Current.Element("nick").Value;
                        }
                        if (items.Current.Element("pic_url") != null)
                        {
                            tmpItem.pic_url = items.Current.Element("pic_url").Value;
                        }
                        if (items.Current.Element("cid") != null)
                        {
                            tmpItem.cid = items.Current.Element("cid").Value;
                        }
                        if (items.Current.Element("price") != null)
                        {
                            tmpItem.price = items.Current.Element("price").Value;
                        }
                        if (items.Current.Element("volume") != null)
                        {
                            tmpItem.volume = items.Current.Element("volume").Value;
                        }
                        if (items.Current.Element("is_prepay") != null)
                        {
                            tmpItem.is_prepay = items.Current.Element("is_prepay").Value;
                        }
                        if (items.Current.Element("promoted_service") != null)
                        {
                            tmpItem.promoted_service = items.Current.Element("promoted_service").Value;
                        }
                        if (items.Current.Element("post_fee") != null)
                        {
                            tmpItem.post_fee = items.Current.Element("post_fee").Value;
                        }
                        if (items.Current.Element("score") != null)
                        {
                            tmpItem.score = items.Current.Element("score").Value;
                        }

                        tmpItemList.Add(tmpItem);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        itemList.Clear();
                        // copy the list over
                        IEnumerator<Item> item = tmpItemList.GetEnumerator();
                        while (item.MoveNext())
                        {
                            itemList.Add(item.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleGetItemResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;
                bool isBrief = true;
                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                if (xmlBasic.Element("item") != null)
                {
                    Item tmpItem = new Item();
                    XElement xmlCurrent = xmlBasic.Descendants("item").First();
                    if (xmlCurrent.Element("wap_detail_url") != null)
                    {
                        tmpItem.wap_detail_url = xmlCurrent.Element("wap_detail_url").Value;
                    }
                    if (xmlCurrent.Element("type") != null)
                    {
                        tmpItem.type = xmlCurrent.Element("type").Value;
                    }
                    if (xmlCurrent.Element("num") != null)
                    {
                        tmpItem.num = xmlCurrent.Element("num").Value;
                    }
                    if (xmlCurrent.Element("stuff_status") != null)
                    {
                        tmpItem.stuff_status = xmlCurrent.Element("stuff_status").Value;
                    }
                    if (xmlCurrent.Element("express_fee") != null)
                    {
                        tmpItem.express_fee = xmlCurrent.Element("express_fee").Value;
                    }
                    if (xmlCurrent.Element("ems_fee") != null)
                    {
                        tmpItem.ems_fee = xmlCurrent.Element("ems_fee").Value;
                    }
                    if (xmlCurrent.Element("freight_payer") != null)
                    {
                        tmpItem.freight_payer = xmlCurrent.Element("freight_payer").Value;
                    }
                    if (xmlCurrent.Element("pic_url") != null)
                    {
                        tmpItem.pic_url = xmlCurrent.Element("pic_url").Value;
                    }
                    if (xmlCurrent.Element("location") != null)
                    {
                        if (xmlCurrent.Element("location").Element("city") != null)
                        {
                            tmpItem.location.city = xmlCurrent.Element("location").Element("city").Value;
                        }
                        if (xmlCurrent.Element("location").Element("state") != null)
                        {
                            tmpItem.location.state = xmlCurrent.Element("location").Element("state").Value;
                        }

                    }
                    if (xmlCurrent.Element("wap_desc") != null)
                    {
                        tmpItem.wap_desc = Utils.removeEmptyLines(xmlCurrent.Element("wap_desc").Value);
                        isBrief = false;
                    }
                    if (isBrief)
                        getItemBriefFinishedEvent(this, new GetItemFinishedEventArgs(tmpItem));
                    else
                        getItemDetialFinishedEvent(this, new GetItemFinishedEventArgs(tmpItem));
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    endLoadingEvent();
                });
                

            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleGetTradeListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);
                totalTrades = 0;

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }
                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }
                
                if (xmlBasic.Element("total_results") != null)
                {
                    totalTrades = Convert.ToInt32(xmlBasic.Element("total_results").Value);
                }
                if (totalTrades == 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                        MessageBox.Show("没有找到任何交易信息");
                    });
                    return;
                }
                ObservableCollection<TradeRecord> tmpTradeList = new ObservableCollection<TradeRecord>();

                if (xmlBasic.Element("trades") != null)
                {
                    XElement xmlCurrent = xmlBasic.Descendants("trades").First();
                    IEnumerator<XElement> trades = xmlCurrent.Descendants("trade").GetEnumerator();
                    while (trades.MoveNext())
                    {
                        TradeRecord tmpTrade = new TradeRecord();
                        if (trades.Current.Element("tid") != null)
                        {
                            tmpTrade.tid = trades.Current.Element("tid").Value;
                        }
                        if (trades.Current.Element("orders") != null)
                        {
                            if (trades.Current.Element("orders").Element("order") != null)
                                if (trades.Current.Element("orders").Element("order").Element("title") != null)
                                    tmpTrade.title = trades.Current.Element("orders").Element("order").Element("title").Value;
                        }
                        if (trades.Current.Element("seller_nick") != null)
                        {
                            tmpTrade.seller_nick = trades.Current.Element("seller_nick").Value;
                        }
                        if (trades.Current.Element("num_iid") != null)
                        {
                            tmpTrade.num_iid = trades.Current.Element("num_iid").Value;
                        }
                        if (trades.Current.Element("status") != null)
                        {
                            tmpTrade.status = trades.Current.Element("status").Value;
                        }
                        tmpTradeList.Add(tmpTrade);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        tradeList.Clear();
                        // copy the list over
                        IEnumerator<TradeRecord> tradeRecord = tmpTradeList.GetEnumerator();
                        while (tradeRecord.MoveNext())
                        {
                            tradeList.Add(tradeRecord.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (InValidSessionException)
            {
                handleInValidSessionException();
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleGetTransFormResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }

                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }
                
                TransForm tmpTransForm = new TransForm();

                if (xmlBasic.Element("out_sid") != null)
                    tmpTransForm.out_sid = xmlBasic.Element("out_sid").Value;
                if (xmlBasic.Element("company_name") != null)
                    tmpTransForm.company_name = xmlBasic.Element("company_name").Value;
                if (xmlBasic.Element("tid") != null)
                    tmpTransForm.tid = xmlBasic.Element("tid").Value;
                if (xmlBasic.Element("status") != null)
                    tmpTransForm.status = xmlBasic.Element("status").Value;

                if (xmlBasic.Element("trace_list") != null)
                {
                    XElement xmlCurrent = xmlBasic.Descendants("trace_list").First();
                    IEnumerator<XElement> transit_step_info = xmlCurrent.Descendants("transit_step_info").GetEnumerator();
                    while (transit_step_info.MoveNext())
                    {
                        TransitStepInfo tmpTransitStepInfo = new TransitStepInfo();
                        tmpTransitStepInfo.color = "LightYellow";
                        if (transit_step_info.Current.Element("status_time") != null)
                        {
                            tmpTransitStepInfo.status_time = transit_step_info.Current.Element("status_time").Value;
                        }
                        if (transit_step_info.Current.Element("status_desc") != null)
                        {
                            tmpTransitStepInfo.status_desc = transit_step_info.Current.Element("status_desc").Value;
                        }
                        tmpTransForm.transitStepInfos.Add(tmpTransitStepInfo);
                    }
                    tmpTransForm.transitStepInfos.Last<TransitStepInfo>().color = "Orange";

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        transForm.out_sid = tmpTransForm.out_sid;
                        transForm.company_name = tmpTransForm.company_name;
                        transForm.tid = tmpTransForm.tid;
                        transForm.status = tmpTransForm.status;
                        // copy the list over
                        IEnumerator<TransitStepInfo> transStep = tmpTransForm.transitStepInfos.GetEnumerator();
                        while (transStep.MoveNext())
                        {
                            transForm.transitStepInfos.Add(transStep.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (InValidSessionException)
            {
                handleInValidSessionException();
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        private void HandleTaokeItemListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }
                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                if (xmlBasic.Element("taobaoke_items") == null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                    });
                    return;
                }
                ObservableCollection<Item> tmpItemList = new ObservableCollection<Item>();


                if (xmlBasic.Element("taobaoke_items") != null)
                {


                    XElement xmlCurrent = xmlBasic.Descendants("taobaoke_items").First();
                    IEnumerator<XElement> items = xmlCurrent.Descendants("taobaoke_item").GetEnumerator();
                    while (items.MoveNext())
                    {
                        Item tmpUser = new Item();
                        if (items.Current.Element("num_iid") != null)
                        {
                            tmpUser.num_iid = items.Current.Element("num_iid").Value;
                        }
                        if (items.Current.Element("pic_url") != null)
                        {
                            tmpUser.pic_url = items.Current.Element("pic_url").Value;
                        }
                        if (items.Current.Element("price") != null)
                        {
                            tmpUser.price = items.Current.Element("price").Value;
                        }
                        if (items.Current.Element("click_url") != null)
                        {
                            tmpUser.wap_detail_url = items.Current.Element("click_url").Value;
                        }

                        tmpItemList.Add(tmpUser);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        taokeItemList.Clear();
                        // copy the list over
                        IEnumerator<Item> item = tmpItemList.GetEnumerator();
                        while (item.MoveNext())
                        {
                            taokeItemList.Add(item.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (InValidSessionException)
            {
                handleInValidSessionException();
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleTradeRateListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);

                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                totalTradeRate = 0;
                if (xmlBasic.Element("total_results") != null)
                {
                    totalTradeRate = Convert.ToInt32(xmlBasic.Element("total_results").Value);
                }
                if (totalTradeRate == 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("目前该商品还没有评论");
                        endLoadingEvent();
                        return;
                    });
                }

                ObservableCollection<TradeRate> tmpTradeRateList = new ObservableCollection<TradeRate>();


                if (xmlBasic.Element("trade_rates") != null)
                {


                    XElement xmlCurrent = xmlBasic.Descendants("trade_rates").First();
                    IEnumerator<XElement> tradeRates = xmlCurrent.Descendants("trade_rate").GetEnumerator();
                    while (tradeRates.MoveNext())
                    {
                        TradeRate tmpTradeRate = new TradeRate();
                        if (tradeRates.Current.Element("tid") != null)
                        {
                            tmpTradeRate.tid = tradeRates.Current.Element("tid").Value;
                        }
                        if (tradeRates.Current.Element("oid") != null)
                        {
                            tmpTradeRate.oid = tradeRates.Current.Element("oid").Value;
                        }
                        if (tradeRates.Current.Element("role") != null)
                        {
                            tmpTradeRate.role = tradeRates.Current.Element("role").Value;
                        }
                        if (tradeRates.Current.Element("nick") != null)
                        {
                            tmpTradeRate.nick = tradeRates.Current.Element("nick").Value;
                        }
                        if (tradeRates.Current.Element("result") != null)
                        {
                            tmpTradeRate.result = tradeRates.Current.Element("result").Value;
                        }
                        if (tradeRates.Current.Element("created") != null)
                        {
                            tmpTradeRate.created = tradeRates.Current.Element("created").Value;
                        }
                        if (tradeRates.Current.Element("rated_nick") != null)
                        {
                            tmpTradeRate.rated_nick = tradeRates.Current.Element("rated_nick").Value;
                        }
                        if (tradeRates.Current.Element("item_title") != null)
                        {
                            tmpTradeRate.item_title = tradeRates.Current.Element("item_title").Value;
                        }
                        if (tradeRates.Current.Element("item_price") != null)
                        {
                            tmpTradeRate.item_price = tradeRates.Current.Element("item_price").Value;
                        }
                        if (tradeRates.Current.Element("content") != null)
                        {
                            tmpTradeRate.content = tradeRates.Current.Element("content").Value;
                        }
                        if (tradeRates.Current.Element("reply") != null)
                        {
                            tmpTradeRate.reply = tradeRates.Current.Element("reply").Value;
                        }
                        if (tradeRates.Current.Element("valid_score") != null)
                        {
                            if ("true".Equals(tradeRates.Current.Element("valid_score").Value))
                                tmpTradeRate.valid_score = true;
                            else
                                tmpTradeRate.valid_score = false;
                        }

                        tmpTradeRateList.Add(tmpTradeRate);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        tradeRateList.Clear();
                        // copy the list over
                        IEnumerator<TradeRate> tradeRate = tmpTradeRateList.GetEnumerator();
                        while (tradeRate.MoveNext())
                        {
                            tradeRateList.Add(tradeRate.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleGetRecentContactorListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();
                
                //StreamReader streamReader = new StreamReader(streamResult, Encoding.UTF8);
                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);
                int totalRecentContactors = 0;

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }
                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                if (xmlBasic.Element("count") != null)
                {
                    totalRecentContactors = Convert.ToInt32(xmlBasic.Element("count").Value);
                }
                if (totalRecentContactors == 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                    });
                    return;
                }
                ObservableCollection<Contactor> tmpContactorList = new ObservableCollection<Contactor>();

                if (xmlBasic.Element("chatpeers") != null)
                {
                    XElement xmlCurrent = xmlBasic.Descendants("chatpeers").First();
                    IEnumerator<XElement> peers = xmlCurrent.Descendants("chatpeer").GetEnumerator();
                    while (peers.MoveNext())
                    {
                        Contactor tmpContactor = new Contactor();
                        if (peers.Current.Element("uid") != null)
                        {
                            tmpContactor.UID = peers.Current.Element("uid").Value;
                            if (tmpContactor.UID.StartsWith("cntaobao"))
                                tmpContactor.nickName = tmpContactor.UID.Substring(8);
                            else
                                tmpContactor.nickName = tmpContactor.UID;
                        }
                        if (peers.Current.Element("date") != null)
                        {
                            tmpContactor.LastDate = peers.Current.Element("date").Value;
                        }
                        if (!tmpContactorList.Contains(tmpContactor))
                            tmpContactorList.Add(tmpContactor);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        recentContactorList.Clear();
                        // copy the list over
                        IEnumerator<Contactor> contactor = tmpContactorList.GetEnumerator();
                        while (contactor.MoveNext())
                        {
                            recentContactorList.Add(contactor.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (InValidSessionException)
            {
                handleInValidSessionException();
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }

        /// <summary>
        /// Handle the information returned from the async request
        /// </summary>
        /// <param name="asyncResult"></param>
        private void HandleGetMessageListResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                //StreamReader streamReader = new StreamReader(streamResult, Encoding.UTF8);
                // load the XML
                XElement xmlBasic = XElement.Load(streamResult);
                int totalMessage = 0;

                if (xmlBasic.Element("code") != null && ("27".Equals(xmlBasic.Element("code").Value) || "25".Equals(xmlBasic.Element("code").Value)))
                {
                    throw new InValidSessionException();
                }
                if (xmlBasic.Element("sub_msg") != null)
                {
                    throw new Exception(xmlBasic.Element("sub_msg").Value);
                }

                if (xmlBasic.Element("count") != null)
                {
                    totalMessage = Convert.ToInt32(xmlBasic.Element("count").Value);
                }
                if (totalMessage == 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        endLoadingEvent();
                    });
                    return;
                }
                ObservableCollection<WangMessage> tmpMessageList = new ObservableCollection<WangMessage>();

                if (xmlBasic.Element("msgs") != null)
                {
                    XElement xmlCurrent = xmlBasic.Descendants("msgs").First();
                    IEnumerator<XElement> peers = xmlCurrent.Descendants("msg").GetEnumerator();
                    while (peers.MoveNext())
                    {
                        WangMessage tmpMessage = new WangMessage();
                        if (peers.Current.Element("direction") != null)
                        {
                            tmpMessage.direction = peers.Current.Element("direction").Value;
                        }
                        if (peers.Current.Element("time") != null)
                        {
                            tmpMessage.time = peers.Current.Element("time").Value;
                        }
                        if (peers.Current.Element("content") != null)
                        {
                            tmpMessage.content = peers.Current.Element("content").Value;
                        }
                        tmpMessageList.Add(tmpMessage);
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        messageList.Clear();
                        // copy the list over
                        IEnumerator<WangMessage> message = tmpMessageList.GetEnumerator();
                        while (message.MoveNext())
                        {
                            messageList.Add(message.Current);
                        }
                        endLoadingEvent();
                    });
                }

            }
            catch (InValidSessionException)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("未知错误");
                });
                return;
            }
            catch (Exception e)
            {
                handleCommonException(e);
                return;
            }

        }
    }

    

    public class filterParams
    {
        private App app = Application.Current as App;
        public string order_by 
        {
            get { return app.filterParams["order_by"]; }
            set { app.filterParams["order_by"] = value; } 
        }
        public string is_prepay
        {
            get { return app.filterParams["is_prepay"]; }
            set { app.filterParams["is_prepay"] = value; }
        }
        public string is_cod
        {
            get { return app.filterParams["is_cod"]; }
            set { app.filterParams["is_cod"] = value; }
        }
        public string promoted_service
        {
            get { return app.filterParams["promoted_service"]; }
            set { app.filterParams["promoted_service"] = value; }
        }
        public string stuff_status
        {
            get { return app.filterParams["stuff_status"]; }
            set { app.filterParams["stuff_status"] = value; }
        }
        public string start_price
        {
            get { return app.filterParams["start_price"]; }
            set { app.filterParams["start_price"] = value; }
        }
        public string end_price
        {
            get { return app.filterParams["end_price"]; }
            set { app.filterParams["end_price"] = value; }
        }

        public filterParams() 
        {
            if (!app.filterParams.ContainsKey("order_by"))
                app.filterParams.Add("order_by", "popularity:desc");
            else 
                app.filterParams["order_by"] = "no";
            if (!app.filterParams.ContainsKey("is_prepay"))
                app.filterParams.Add("is_prepay", "no");
            else
                app.filterParams["is_prepay"] = "no";
            if (!app.filterParams.ContainsKey("is_cod"))
                app.filterParams.Add("is_cod", "no");
            else
                app.filterParams["is_cod"] = "no";
            if (!app.filterParams.ContainsKey("promoted_service"))
                app.filterParams.Add("promoted_service", "no");
            else
                app.filterParams["promoted_service"] = "no";
            if (!app.filterParams.ContainsKey("stuff_status"))
                app.filterParams.Add("stuff_status", "no");
            else
                app.filterParams["stuff_status"] = "no";
            if (!app.filterParams.ContainsKey("start_price"))
                app.filterParams.Add("start_price", "no");
            else
                app.filterParams["start_price"] = "no";
            if (!app.filterParams.ContainsKey("end_price"))
                app.filterParams.Add("end_price", "no");
            else
                app.filterParams["end_price"] = "no";
        }
    }

}
